package com.spring.sunflower.conversation;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.blankj.utilcode.util.SizeUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.lxj.xpopup.XPopup;
import com.makeramen.roundedimageview.RoundedImageView;
import com.opensource.svgaplayer.SVGACallback;
import com.opensource.svgaplayer.SVGAImageView;
import com.spring.sunflower.BuildConfig;
import com.spring.sunflower.R;
import com.spring.sunflower.base.BaseActivity;
import com.spring.sunflower.bean.AnchorDetailBean;
import com.spring.sunflower.bean.BeautyConfigBean;
import com.spring.sunflower.bean.ChatGiftBean;
import com.spring.sunflower.bean.CustomMessageBean;
import com.spring.sunflower.bean.LiveApplyChatBean;
import com.spring.sunflower.bean.MessageCustomEntity;
import com.spring.sunflower.common.WalletActivity;
import com.spring.sunflower.constant.Constant;
import com.spring.sunflower.conversation.beauty.model.BeautyInfo;
import com.spring.sunflower.conversation.beauty.utils.BeautyUtils;
import com.spring.sunflower.conversation.beauty.view.BeautyPanel;
import com.spring.sunflower.dialog.NoticeDialog;
import com.spring.sunflower.dialog.OnPermissionIntroClickListener;
import com.spring.sunflower.event.BaseChatEvent;
import com.spring.sunflower.event.CallRequestCancelEvent;
import com.spring.sunflower.event.GiftSendEvent;
import com.spring.sunflower.event.GiftSendSuccessEvent;
import com.spring.sunflower.event.JoinRoomEvent;
import com.spring.sunflower.event.LastChatEvent;
import com.spring.sunflower.event.NeedChargeEvent;
import com.spring.sunflower.event.RoomClosedEvent;
import com.spring.sunflower.util.AppUtils;
import com.spring.sunflower.util.CallRingtoneUtils;
import com.spring.sunflower.util.DisplayUtils;
import com.spring.sunflower.util.VideoViewOutlineProvider;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMSendCallback;
import com.tencent.liteav.beauty.TXBeautyManager;
import com.tencent.liteav.device.TXDeviceManager;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.trtc.TRTCCloud;
import com.tencent.trtc.TRTCCloudDef;
import com.tencent.trtc.TRTCCloudListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import jp.wasabeef.glide.transformations.BlurTransformation;

import static com.tencent.trtc.TRTCCloudDef.TRTC_APP_SCENE_VIDEOCALL;
import static com.tencent.trtc.TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT;
import static com.tencent.trtc.TRTCCloudDef.TRTC_AUDIO_ROUTE_SPEAKER;
import static com.tencent.trtc.TRTCCloudDef.TRTC_VIDEO_RENDER_MODE_FILL;

/**
 * Created by Kevin on 2021/7/15<br/>
 * <p>
 * Describe:<br/>
 */
public class ChatVideoActivity extends BaseActivity<ChatVideoPresenter> implements ChatVideoView, View.OnClickListener {
    private TXCloudVideoView txLocalVideoView, txRemoteVideoView;
    private ImageView ivAccept, ivHangup, ivRefuse, ivMicro, ivAudio;
    private ImageView ivGift, ivBeauty;
    private ImageView ivBlurBackground;
    private ConstraintLayout clHangupContainer, clAcceptRefuseContainer;
    private RoundedImageView rivAvatar, rivAvatarH;
    private LinearLayout llAvatarContainerV, llAvatarContainerH;
    private TextView tvNickname, tvStatus, tvNicknameH, tvTime, tvTip;
    private TRTCCloud mTRTCCloud;
    private String mUserId;
    private String mUserSig;
    private String mOtherId, mOtherFaceUrl, mOtherNickname;
    private RelativeLayout rlContainer;
    private LinearLayout llBeauty;
    /**
     * 电话已接通
     */
    private boolean isConnected = false;
    private boolean isSelfDial;
    private int mRoomId;
    private String mGender;
    private Timer verifyTimer;
    private Timer callTimer;
    private boolean isLocalAudioEnable = true, isRemoteAudioEnable = true, isLoudSpeaker = true;
    private boolean isLocalViewBig = true;//默认本地画面为大画面
    private int mScreenWidth;
    private int mScreenHeight, mScreenRealHeight;
    private RelativeLayout.LayoutParams mBigLayoutParams;
    private RelativeLayout.LayoutParams mSmallLayoutParams;
    private int marginHorizontal;
    private int marginTop;
    private int marginBottom;
    private int mSmallWidth;
    private int mSmallHeight;
    private List<ChatGiftBean.Data> mGiftList = new ArrayList();
    private String money;
    private int giftSelectPos = 0;
    private SVGAImageView mSVGAPlayer;
    private BottomGiftDialog giftDialog;
    private int mTimerSecond;
    private BeautyPanel beautyPanel;
    private boolean isFrontCamera = true;
    private int filterIndex = 1;//滤镜的索引
    private LinearLayout llGift, llFunction;
    private List<String> svgaSource = new ArrayList<>();
    private boolean allButtonShow = true;
    //是否仅显示弹窗
    private boolean isCallReceiveShow = false;
    private Handler handler = new Handler();
    private Runnable runnable;
    SVGACallback svgaCallback = new SVGACallback() {

        @Override
        public void onStep(int frame, double percentage) {

        }

        @Override
        public void onRepeat() {

        }

        @Override
        public void onPause() {

        }

        @Override
        public void onFinished() {
            if (svgaSource.size() > 1) {
                svgaSource.remove(0);
                String s = svgaSource.get(0);
                ConversationManager.playSVGA(ChatVideoActivity.this, mSVGAPlayer, s);
            } else if (svgaSource.size() > 0) {
                svgaSource.remove(0);
            }
        }
    };

    @Override
    public void doSomethingBeforeOnCreate() {
        super.doSomethingBeforeOnCreate();
        Window window = getWindow();
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
    }

    @Override
    public void initView() {
        Constant.shouldShowLuckyMatchDialog = false;
        Constant.isInCall = true;
        mScreenWidth = DisplayUtils.getScreenWidth(this);
        mScreenHeight = DisplayUtils.getScreenHeight(this);
        mScreenRealHeight = DisplayUtils.getRealScreenHeight(this);
        Intent intent = getIntent();
        isSelfDial = intent.getBooleanExtra(Constant.VIDEO_CALL_SELF_DIAL, false);
        mOtherId = intent.getStringExtra(Constant.VIDEO_CALL_OTHER_ID);
        isCallReceiveShow = intent.getBooleanExtra(Constant.VIDEO_CALL_SHOW, false);
        saveField(Constant.KEY_USERID_CHATTER, mOtherId);
        if (TextUtils.isEmpty(mOtherId)) {
            showToast("无法获取有效信息，请重试");
            hangupThisCall();
//            mOtherId = getField(Constant.KEY_USERID_CHATTER, "");
        }
        mOtherFaceUrl = intent.getStringExtra(Constant.VIDEO_CALL_OTHER_FACE_URL);
        if (TextUtils.isEmpty(mOtherFaceUrl)) {
            mOtherFaceUrl = getField(Constant.KEY_AVATAR_CHATTER, "");
        }
        mOtherNickname = intent.getStringExtra(Constant.VIDEO_CALL_OTHER_NICKNAME);
        if (TextUtils.isEmpty(mOtherNickname)) {
            mOtherNickname = getField(Constant.KEY_NICKNAME_CHATTER, "");
        }

        mGender = getField(Constant.KEY_GENDER, "1");
        mUserId = getField(Constant.KEY_USERID, "");
        mUserSig = getField(Constant.KEY_SIGNATURE, "");

        mPresenter.loadAllGift();
        mPresenter.getDetail(mUserId);

        llAvatarContainerH = findViewById(R.id.llAvatarContainerH);
        llAvatarContainerV = findViewById(R.id.llAvatarContainerV);
        rivAvatar = findViewById(R.id.rivAvatar);
        rivAvatarH = findViewById(R.id.rivAvatarH);
        tvNickname = findViewById(R.id.tvNickname);
        tvNicknameH = findViewById(R.id.tvNicknameH);
        Glide.with(this).load(mOtherFaceUrl).into(rivAvatar);
        Glide.with(this).load(mOtherFaceUrl).into(rivAvatarH);
        tvNickname.setText(mOtherNickname);
        tvNicknameH.setText(mOtherNickname);
        tvStatus = findViewById(R.id.tvStatus);
        tvStatus.setText("等待接听中...");
        showVerticalAvatar();
        rlContainer = findViewById(R.id.rlContainer);
        txLocalVideoView = findViewById(R.id.txLocalVideoView);
        txRemoteVideoView = findViewById(R.id.txRemoteVideoView);
        ivBlurBackground = findViewById(R.id.ivBlurBackground);
        ivAccept = findViewById(R.id.iv_accept);
        ivHangup = findViewById(R.id.iv_hangup);
        ivRefuse = findViewById(R.id.iv_refuse);
        ivAudio = findViewById(R.id.iv_audio);
        ivMicro = findViewById(R.id.iv_micro);
        ivGift = findViewById(R.id.iv_gift);
        ivBeauty = findViewById(R.id.iv_beauty);
        llBeauty = findViewById(R.id.llBeauty);
        llGift = findViewById(R.id.llGift);
        llGift.setVisibility(View.INVISIBLE);
        llFunction = findViewById(R.id.llFunction);
        clHangupContainer = findViewById(R.id.clHangupContainer);
        clAcceptRefuseContainer = findViewById(R.id.clAcceptRefuse);
        tvTip = findViewById(R.id.tvTip);
        tvTime = findViewById(R.id.tvTime);
        mSVGAPlayer = findViewById(R.id.svgaPlayer);
        mSVGAPlayer.setCallback(svgaCallback);
        ivAccept.setOnClickListener(this);
        ivHangup.setOnClickListener(this);
        ivRefuse.setOnClickListener(this);
        ivMicro.setOnClickListener(this);
        ivAudio.setOnClickListener(this);
        ivGift.setOnClickListener(this);
        ivBeauty.setOnClickListener(this);
        llBeauty.setOnClickListener(this);
        txLocalVideoView.setOnClickListener(this);
        txRemoteVideoView.setOnClickListener(this);
        Glide.with(this)
                .load(mOtherFaceUrl)
                .apply(RequestOptions.bitmapTransform(new BlurTransformation(25, 5)))
                .into(ivBlurBackground);
        if (isSelfDial) {
            showHangup();
        } else {
            showAcceptAndRefuse();
        }
        if (isCallReceiveShow) {//假视频，不操作的话59秒后自动取消
            llBeauty.setVisibility(View.GONE);
            runnable = new Runnable() {
                @Override
                public void run() {
                    hangupThisCall();
                }
            };
            handler.postDelayed(runnable, 59000);
        } else {
            llBeauty.setVisibility(View.VISIBLE);
            mTRTCCloud = TRTCCloud.sharedInstance(this);
            mTRTCCloud.setListener(mTRTCCloudListener);
            if (BuildConfig.DEBUG) {
                TRTCCloud.setConsoleEnabled(true);
            } else {
                TRTCCloud.setConsoleEnabled(false);
            }

            marginHorizontal = SizeUtils.dp2px(15);
            marginTop = SizeUtils.dp2px(50);
            marginBottom = SizeUtils.dp2px(120);
            mBigLayoutParams = new RelativeLayout.LayoutParams(-1, -1);
            mSmallWidth = SizeUtils.dp2px(100);
            mSmallHeight = mSmallWidth * mScreenHeight / mScreenWidth;
            mSmallLayoutParams = new RelativeLayout.LayoutParams(mSmallWidth, mSmallHeight);
            mSmallLayoutParams.setMargins(mScreenWidth - mSmallWidth - marginHorizontal, marginTop, 0, 0);
            txRemoteVideoView.setLayoutParams(mSmallLayoutParams);
            setOutLineLocalViewBig(txRemoteVideoView, txLocalVideoView);
            initGestureListener();
            initBeauty();
        }
        CallRingtoneUtils.getInstance(this).playCallRingtone();
    }

    private void initBeauty() {
        String beautyJson = getField(Constant.KEY_BEAUTY_CONFIG, "");
        if (TextUtils.isEmpty(beautyJson)) {
            beautyJson = BeautyUtils.readAssetsFile("default_beauty_data.json");
        } else {
            BeautyConfigBean bean = new Gson().fromJson(beautyJson, BeautyConfigBean.class);
            filterIndex = bean.getBeautyTabList().get(1).getCurrentSelectFilterIndex();
        }
        Constant.tempBeautyConfig = beautyJson;
        saveField(Constant.KEY_BEAUTY_CONFIG, beautyJson);
//        String beautyJson = BeautyUtils.readAssetsFile("default_beauty_data.json");
        BeautyInfo beautyInfo = BeautyUtils.createBeautyInfo(beautyJson);
        beautyPanel = new BeautyPanel(this);
        beautyPanel.setBeautyInfo(beautyInfo);
        beautyPanel.setBeautyManager(mTRTCCloud.getBeautyManager());
        beautyPanel.setCurrentFilterIndex(filterIndex);
        beautyPanel.setCurrentBeautyIndex(0);
    }

    public void showVerticalAvatar() {
        llAvatarContainerH.setVisibility(View.GONE);
        llAvatarContainerV.setVisibility(View.VISIBLE);
    }

    public void showHorizontalAvatar() {
        llAvatarContainerH.setVisibility(View.VISIBLE);
        llAvatarContainerV.setVisibility(View.GONE);
    }

    public void switchVideoView() {
        if (isLocalViewBig) {
            isLocalViewBig = false;
            txRemoteVideoView.setLayoutParams(mBigLayoutParams);
            txLocalVideoView.setLayoutParams(mSmallLayoutParams);
            setOutLineLocalViewBig(txLocalVideoView, txRemoteVideoView);
            rlContainer.bringChildToFront(txLocalVideoView);
        } else {
            isLocalViewBig = true;
            txRemoteVideoView.setLayoutParams(mSmallLayoutParams);
            txLocalVideoView.setLayoutParams(mBigLayoutParams);
            setOutLineLocalViewBig(txRemoteVideoView, txLocalVideoView);
            rlContainer.bringChildToFront(txRemoteVideoView);
        }
    }

    public void setOutLineLocalViewBig(TXCloudVideoView txSmallView, TXCloudVideoView txBigView) {
        txSmallView.setOutlineProvider(new VideoViewOutlineProvider(15));
        txBigView.setOutlineProvider(new VideoViewOutlineProvider(0));
    }

    /**
     * 显示接听拒绝按钮
     */
    public void showAcceptAndRefuse() {
//        ivAccept.setVisibility(View.VISIBLE);
//        ivRefuse.setVisibility(View.VISIBLE);
//        ivHangup.setVisibility(View.GONE);
        clAcceptRefuseContainer.setVisibility(View.VISIBLE);
        clHangupContainer.setVisibility(View.GONE);
    }

    /**
     * 显示挂断按钮
     */
    public void showHangup() {
//        ivAccept.setVisibility(View.GONE);
//        ivRefuse.setVisibility(View.GONE);
//        ivHangup.setVisibility(View.VISIBLE);
        clAcceptRefuseContainer.setVisibility(View.GONE);
        clHangupContainer.setVisibility(View.VISIBLE);
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_chat_video;
    }

    @Override
    public ChatVideoPresenter setPresenter() {
        return new ChatVideoPresenter(this);
    }

    @Override
    public boolean shouldRegisterEventBus() {
        return true;
    }

    private void onlineVerify() {
        verifyTimer = new Timer();
        verifyTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                mPresenter.onlineVerify(String.valueOf(mRoomId));
            }
        }, 0, 10000);
    }

    private void startTimer() {
        callTimer = new Timer();
        callTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                ++mTimerSecond;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvTime.setText(AppUtils.formatTime(mTimerSecond));
                    }
                });

            }
        }, 0, 1000);
    }

    private void enterRoom(int roomId) {
        String environment = getField(Constant.KEY_ENVIRONMENT, Constant.ENVIRONMENT_PRODUCT);
        TRTCCloudDef.TRTCParams trtcParams = new TRTCCloudDef.TRTCParams();
        trtcParams.sdkAppId = environment.equals(Constant.ENVIRONMENT_PRODUCT) ? Constant.TRTC_APPID_PRODUCT : Constant.TRTC_APPID_TEST;
        trtcParams.userId = mUserId;
        trtcParams.roomId = roomId;
        trtcParams.userSig = mUserSig;
        mTRTCCloud.enterRoom(trtcParams, TRTC_APP_SCENE_VIDEOCALL);
        //示例代码：发布本地的音视频流
        mTRTCCloud.setLocalViewFillMode(TRTC_VIDEO_RENDER_MODE_FILL);
        TRTCCloudDef.TRTCRenderParams trtcRenderParams = new TRTCCloudDef.TRTCRenderParams();
//        trtcRenderParams.fillMode = TRTC_VIDEO_RENDER_MODE_FILL;
//        mTRTCCloud.setLocalRenderParams(trtcRenderParams);
        mTRTCCloud.startLocalPreview(true, txLocalVideoView);
        mTRTCCloud.startLocalAudio();
        mTRTCCloud.setAudioRoute(TRTC_AUDIO_ROUTE_SPEAKER);
        TXBeautyManager beautyManager = mTRTCCloud.getBeautyManager();
//        beautyManager.set

    }

    private TRTCCloudListener mTRTCCloudListener = new TRTCCloudListener() {
        @Override
        public void onError(int errCode, String errMsg, Bundle extraInfo) {
//            TRTCLogger.e(TAG, "onError: " + errCode + " " + errMsg);
//            stopCall();
//            if (mTRTCInternalListenerManager != null) {
//                mTRTCInternalListenerManager.onError(errCode, errMsg);
//            }
        }

        @Override
        public void onEnterRoom(long result) {
//            TRTCLogger.d(TAG, "onEnterRoom result:" + result);
            if (result < 0) {
//                stopCall();
                hangupThisCall();
            } else {//进入房间后调用在线认证
//                mIsInRoom = true;
                onlineVerify();
                if (isSelfDial) {
                    showHorizontalAvatar();
                }
            }
        }

        @Override
        public void onExitRoom(int reason) {
//            TRTCLogger.d(TAG, "onExitRoom reason:" + reason);
            isConnected = false;
        }

        @Override
        public void onRemoteUserEnterRoom(String userId) {
//            TRTCLogger.d(TAG, "onRemoteUserEnterRoom userId:" + userId);
//            mCurRoomRemoteUserSet.add(userId);
            // 只有单聊这个时间才是正确的，因为单聊只会有一个用户进群，群聊这个时间会被后面的人重置
//            mEnterRoomTime = System.currentTimeMillis();
//            if (mTRTCInternalListenerManager != null) {
//                mTRTCInternalListenerManager.onUserEnter(userId);
//            }
        }

        @Override
        public void onRemoteUserLeaveRoom(String userId, int reason) {
//            TRTCLogger.d(TAG, "onRemoteUserLeaveRoom userId:" + userId + ", reason:" + reason);
//            mCurRoomRemoteUserSet.remove(userId);
//            mCurInvitedList.remove(userId);
//            // 远端用户退出房间，需要判断本次通话是否结束
//            if (mTRTCInternalListenerManager != null) {
//                mTRTCInternalListenerManager.onUserLeave(userId);
//            }
//            preExitRoom(userId);
        }

        @Override
        public void onUserVideoAvailable(String userId, boolean available) {
//            TRTCLogger.d(TAG, "onUserVideoAvailable userId:" + userId + ", available:" + available);
//            if (mTRTCInternalListenerManager != null) {
//                mTRTCInternalListenerManager.onUserVideoAvailable(userId, available);
//            }
            if (available) {
                CallRingtoneUtils.getInstance(ChatVideoActivity.this).stop();
                showToast("已接通");
                startTimer();
                tvTip.setVisibility(View.GONE);
                mTRTCCloud.setRemoteViewFillMode(userId, TRTC_VIDEO_RENDER_MODE_FILL);
                mTRTCCloud.startRemoteView(userId, txRemoteVideoView);
                isConnected = true;
                llGift.setVisibility(View.VISIBLE);
                showHangup();
            } else {
                mTRTCCloud.stopRemoteView(userId);

            }
        }

        @Override
        public void onUserAudioAvailable(String userId, boolean available) {
//            TRTCLogger.d(TAG, "onUserAudioAvailable userId:" + userId + ", available:" + available);
//            if (mTRTCInternalListenerManager != null) {
//                mTRTCInternalListenerManager.onUserAudioAvailable(userId, available);
//            }
        }

        @Override
        public void onUserVoiceVolume(ArrayList<TRTCCloudDef.TRTCVolumeInfo> userVolumes, int totalVolume) {
//            Map<String, Integer> volumeMaps = new HashMap<>();
//            for (TRTCCloudDef.TRTCVolumeInfo info : userVolumes) {
//                String userId = "";
//                if (info.userId == null) {
//                    userId = mCurUserId;
//                } else {
//                    userId = info.userId;
//                }
//                volumeMaps.put(userId, info.volume);
//            }
//            mTRTCInternalListenerManager.onUserVoiceVolume(volumeMaps);
        }
    };

    private void hangupThisCall() {
        CallRingtoneUtils.getInstance(this).playHangUp();
        if (mTRTCCloud != null) {
            mTRTCCloud.stopAllRemoteView();
            mTRTCCloud.stopLocalAudio();
            mTRTCCloud.stopLocalPreview();
            mTRTCCloud.muteAllRemoteAudio(true);
            mTRTCCloud.exitRoom();
            TRTCCloud.destroySharedInstance();
        }
        onBackPressed();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_accept:
                if (isFastClick()) return;
                if (isCallReceiveShow) {
                    showNeedChargeDialog(true);
                    return;
                }
                if (!XXPermissions.isGranted(this, Permission.RECORD_AUDIO) || !XXPermissions.isGranted(this, Permission.CAMERA)) {
                    showPermissionIntroDialog(new String[]{getString(R.string.permission_audio_title), getString(R.string.permission_camera_title)}, new String[]{getString(R.string.permission_audio_desc), getString(R.string.permission_camera_desc)}, new OnPermissionIntroClickListener() {
                        @Override
                        public void onClickOK() {
                            XXPermissions.with(ChatVideoActivity.this)
                                    .permission(Permission.RECORD_AUDIO, Permission.CAMERA)
                                    .request(new OnPermissionCallback() {
                                        @Override
                                        public void onGranted(List<String> permissions, boolean all) {
                                            if (all) {
                                                mPresenter.accept(mUserId, mOtherId);
                                                showHorizontalAvatar();
                                            } else {
                                                showPermissionIntroDialog(getString(R.string.permission_denied_title), "无法正常进行视频通话", null);
                                            }
                                        }

                                        @Override
                                        public void onDenied(List<String> permissions, boolean never) {
                                            showPermissionIntroDialog(getString(R.string.permission_denied_title), "无法正常进行视频通话", null);
                                        }
                                    });
                        }

                        @Override
                        public void onClickCancel() {

                        }
                    });
                } else {
                    mPresenter.accept(mUserId, mOtherId);
                    showHorizontalAvatar();
                }
                break;
            case R.id.iv_hangup:
                if (isFastClick()) return;
                if (isCallReceiveShow) {
                    mPresenter.callShowHangup(mOtherId);
                    return;
                }
                if (isConnected) {
                    mPresenter.hangup(String.valueOf(mRoomId));
                } else {
                    mPresenter.cancel(mUserId, mOtherId);
                }
                break;
            case R.id.iv_refuse:
                if (isFastClick()) return;
                mPresenter.refuse(mUserId, mOtherId);
                break;
            case R.id.iv_micro:
                if (isLocalAudioEnable) {
                    isLocalAudioEnable = false;
                    mTRTCCloud.stopLocalAudio();
                    ivMicro.setBackgroundResource(R.drawable.ic_bg_call_button_transparent);
                    ivMicro.setImageResource(R.drawable.ic_call_micro_mute);
                    ivMicro.setColorFilter(0xffffffff);
                    showToast("麦克风已关");
                } else {
                    isLocalAudioEnable = true;
                    mTRTCCloud.startLocalAudio(TRTC_AUDIO_QUALITY_DEFAULT);
                    ivMicro.setBackgroundResource(R.drawable.ic_bg_call_button_white);
                    ivMicro.setImageResource(R.drawable.ic_call_micro_normal);
                    ivMicro.setColorFilter(0xffFADB4A);
                    showToast("麦克风已开");
                }
                break;
            case R.id.iv_audio:
                TXDeviceManager deviceManager = mTRTCCloud.getDeviceManager();
                if (deviceManager.isFrontCamera()) {
                    deviceManager.switchCamera(false);
                    ivAudio.setBackgroundResource(R.drawable.ic_bg_call_button_transparent);
                    ivAudio.setColorFilter(0xffffffff);
                } else {
                    deviceManager.switchCamera(true);
                    ivAudio.setBackgroundResource(R.drawable.ic_bg_call_button_white);
                    ivAudio.setColorFilter(0xffFADB4A);
                }
//                if (isLoudSpeaker) {
//                    isLoudSpeaker = false;
//                    mTRTCCloud.setAudioRoute(TRTC_AUDIO_ROUTE_EARPIECE);
//                    ivAudio.setBackgroundResource(R.drawable.ic_bg_circle_transparent);
//                    ivAudio.setImageResource(R.drawable.ic_call_audio_mute);
//                    ivAudio.setColorFilter(0xffffffff);
//                    showToast("扬声器已关");
//                } else {
//                    isLoudSpeaker = true;
//                    mTRTCCloud.setAudioRoute(TRTC_AUDIO_ROUTE_SPEAKER);
//                    ivAudio.setBackgroundResource(R.drawable.ic_btn_bg_white);
//                    ivAudio.setImageResource(R.drawable.ic_call_audio_normal);
//                    ivAudio.setColorFilter(0xfffeac00);
//                    showToast("扬声器已开");
//                }
                break;
            case R.id.iv_gift:
                if (isFastClick()) return;
                giftDialog = new BottomGiftDialog(mGiftList, money, this);
                giftDialog.setOnGiftActionListener(new BottomGiftDialog.OnGiftActionListener() {
                    @Override
                    public void onGiftSelect(int position) {
                        giftSelectPos = position;
                    }

                    @Override
                    public void onSendGift(@NonNull Map<String, String> map, int pos) {
                        printD("onSendGift=============");
                        mPresenter.sendGift(map, pos);
                    }

                    @Override
                    public void onChargeClick() {
                        Intent intent = new Intent(ChatVideoActivity.this, WalletActivity.class);
                        startActivity(intent);
                    }
                });
                new XPopup.Builder(this)
                        .enableDrag(false)
                        .hasShadowBg(false)
//                        .hasBlurBg(true)
                        .asCustom(giftDialog)
                        .show();
                break;
            case R.id.iv_beauty:
            case R.id.llBeauty:
                if (isFastClick()) return;
                if (beautyPanel != null) {
                    beautyPanel.show();
                }
                break;
            case R.id.txLocalVideoView:
                if (isLocalViewBig) {

                } else {
                    switchVideoView();
                }
                break;
            case R.id.txRemoteVideoView:
                if (isLocalViewBig) {
                    switchVideoView();
                } else {

                }
                break;
        }
    }

    public void processAvatar() {
//        int top = rivAvatar.getTop();
//        int left = rivAvatar.getLeft();
//        int endTop = DisplayUtils.dip2px(this, 50);
//        int endLeft = DisplayUtils.dip2px(this, 15);
//        ObjectAnimator translationX = ObjectAnimator.ofFloat(rivAvatar, "translationX", endLeft - left);
//        ObjectAnimator translationY = ObjectAnimator.ofFloat(rivAvatar, "translationY", endTop - top);
//        ObjectAnimator scaleX = ObjectAnimator.ofFloat(rivAvatar, "scaleX", 1, 0.5f);
//        ObjectAnimator scaleY = ObjectAnimator.ofFloat(rivAvatar, "scaleY", 1, 0.5f);
//        AnimatorSet animatorSet = new AnimatorSet();
//        animatorSet.playTogether(translationX, translationY, scaleX, scaleY);
//        animatorSet.setDuration(1000);
//        animatorSet.start();
    }

    @Override
    public void acceptSuccess(String roomId) {
        CallRingtoneUtils.getInstance(this).playAccept();
        mRoomId = Integer.valueOf(roomId);
        enterRoom(mRoomId);
    }

    @Override
    public void refuseSuccess() {
        hangupThisCall();
    }

    @Override
    public void cancelSuccess() {
        hangupThisCall();
    }

    @Override
    public void hangupSuccess() {
        hangupThisCall();

    }

    @Override
    public void showGiftList(List<ChatGiftBean.Data> data) {
        if (data != null) {
            data.get(0).setChecked(true);
        }
        mGiftList = data;
    }

    @Override
    public void showAnchorData(AnchorDetailBean.DatasBean data) {
        if (data == null) {
            money = "0";
        } else {
            money = data.getMoney();
        }
        saveField(Constant.KEY_MONEY, data.getMoney());
    }

    @Override
    public void sendGiftSuccess(String money, int pos) {
//        tvMoney?.text = money
        giftDialog.updateMoney(money);
        saveField(Constant.KEY_MONEY, money);
        GiftSendSuccessEvent giftSendSuccessEvent = new GiftSendSuccessEvent();
//        int d = giftSelectPos;
        ChatGiftBean.Data data = mGiftList.get(pos);
        giftSendSuccessEvent.setGiftPath(data.getImagePath());
        giftSendSuccessEvent.setGiftEffect(data.getEffects());
        giftSendSuccessEvent.setGiftName(data.getName());
        giftSendSuccessEvent.setGiftNum("1");
//        EventBus.getDefault().post(giftSendSuccessEvent);

        BaseChatEvent<GiftSendSuccessEvent> chatEvent = new BaseChatEvent<>();
        chatEvent.setEvent(giftSendSuccessEvent);
        processSendMessage("【礼物】", Constant.CUSTOM_MESSAGE_GIFT, chatEvent);

    }

    @Override
    public void sendGiftFailed(String msg) {
        showToast("发送失败" + msg);
    }

    public void showOrHideButton() {
        float hangupContainerTop = clHangupContainer.getTop();
        float avatarContainerHBottom = llAvatarContainerH.getBottom();
        float distance = mScreenRealHeight - hangupContainerTop + 100;
        if (allButtonShow) {
            allButtonShow = false;
            AnimatorSet animatorSet = new AnimatorSet();
            ObjectAnimator animator = ObjectAnimator.ofFloat(llFunction, "alpha", 0);
            ObjectAnimator animator1 = ObjectAnimator.ofFloat(clHangupContainer, "translationY", 0, distance);
            ObjectAnimator animator2 = ObjectAnimator.ofFloat(llAvatarContainerH, "translationY", 0, -avatarContainerHBottom);
            animatorSet.playTogether(animator, animator1, animator2);
            animatorSet.setDuration(300);
            animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
            animatorSet.start();

        } else {
            allButtonShow = true;
            AnimatorSet animatorSet = new AnimatorSet();
            ObjectAnimator animator = ObjectAnimator.ofFloat(llFunction, "alpha", 1);
            ObjectAnimator animator1 = ObjectAnimator.ofFloat(clHangupContainer, "translationY", distance, 0);
            ObjectAnimator animator2 = ObjectAnimator.ofFloat(llAvatarContainerH, "translationY", -avatarContainerHBottom, 0);
            animatorSet.playTogether(animator, animator1, animator2);
            animatorSet.setDuration(300);
            animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
            animatorSet.start();
        }

    }

    private void processSendMessage(String content, String type, BaseChatEvent event) {
        ConversationManager.sendMessage(content, type, event, new V2TIMSendCallback<V2TIMMessage>() {
            @Override
            public void onProgress(int progress) {

            }

            @Override
            public void onError(int code, String desc) {
                printD("code=" + code + ",desc=" + desc);
                showToast("发送失败");
            }

            @Override
            public void onSuccess(V2TIMMessage v2TIMMessage) {
//                printD(content + "发送成功");
                refreshChatList(v2TIMMessage, true);
                LastChatEvent lastChatEvent = new LastChatEvent();
                lastChatEvent.setUserID(mOtherId);
                EventBus.getDefault().post(lastChatEvent);
            }
        });
    }

    public void refreshChatList(V2TIMMessage msg, boolean isSend) {
//        MessageEntity messageEntity = V2TIMMessageConvertToMessageEntity(msg);
        ChatCustomAdapter adapter = ChatActivity.getAdapter();
        CustomMessageBean bean = ConversationManager.processV2TIMMessage(msg);
        if (isSend) {
            MessageCustomEntity messageCustomEntity = ConversationManager.customMessageBean2MessageCustomEntity(bean, msg);
            if (messageCustomEntity != null && adapter != null) {
                adapter.addData(messageCustomEntity);
                ChatActivity.scrollToEnd();
            }
        } else {
            if (bean != null) {
                if (bean.data != null) {
                    if (bean.data.fromUser.memberId.equals(mOtherId)) {
                        MessageCustomEntity messageCustomEntity = ConversationManager.customMessageBean2MessageCustomEntity(bean, msg);
                        if (messageCustomEntity != null && adapter != null) {
                            adapter.addData(messageCustomEntity);
                            ChatActivity.scrollToEnd();
                        }
                    } else {
                    }
                }
            }
        }
    }

    public static void onCallReceive(Context context, LiveApplyChatBean.Datas data) {
        Intent intent = new Intent(context, ChatVideoActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Constant.VIDEO_CALL_SELF_DIAL, false);
        intent.putExtra(Constant.VIDEO_CALL_OTHER_ID, data.getSender());
        intent.putExtra(Constant.VIDEO_CALL_OTHER_FACE_URL, data.getPhoto());
        intent.putExtra(Constant.VIDEO_CALL_OTHER_NICKNAME, data.getNickname());
        intent.putExtra(Constant.VIDEO_CALL_SHOW, false);
        context.startActivity(intent);
    }

    /**
     * 男方收到呼叫推送，点击接听去充值
     * 审核环境不谈
     *
     * @param context
     * @param data
     */
    public static void onCallReceiveShow(Context context, LiveApplyChatBean.Datas data) {
        Intent intent = new Intent(context, ChatVideoActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(Constant.VIDEO_CALL_SELF_DIAL, false);
        intent.putExtra(Constant.VIDEO_CALL_OTHER_ID, data.getSender());
        intent.putExtra(Constant.VIDEO_CALL_OTHER_FACE_URL, data.getPhoto());
        intent.putExtra(Constant.VIDEO_CALL_OTHER_NICKNAME, data.getNickname());
        intent.putExtra(Constant.VIDEO_CALL_SHOW, true);
        context.startActivity(intent);
    }

    /**
     * 对方接听
     *
     * @param event
     */
    @Subscribe
    public void thereAccept(JoinRoomEvent event) {
        mRoomId = event.getRoomId();
        enterRoom(mRoomId);
    }

    @Subscribe
    public void inviteCancel(CallRequestCancelEvent event) {
        hangupThisCall();
    }

    @Subscribe
    public void chatRoomClosed(RoomClosedEvent event) {
        printD("chatRoomClosed::" + event.getMessage());
        hangupThisCall();
    }

    @Subscribe
    public void giftEffectShow(GiftSendEvent event) {
        //第一个过来 size=0,添加进来，然后播放，播放完毕移除第一个
        if (svgaSource.size() >= 1) {
            svgaSource.add(event.getEffects());
        } else {
            svgaSource.add(event.getEffects());
            ConversationManager.playSVGA(this, mSVGAPlayer, event.getEffects());
        }
    }

    @Subscribe
    public void needCharge(NeedChargeEvent event) {
        String message = event.getMessage();
        int minute = event.getMinute();
        NoticeDialog dialog = showNoticeDialog("温馨提醒", "余额提醒", "当前余额不足1分钟", "去充值", new OnPermissionIntroClickListener() {
            @Override
            public void onClickCancel() {
            }

            @Override
            public void onClickOK() {
                Intent intent = new Intent(ChatVideoActivity.this, WalletActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (verifyTimer != null) {
            verifyTimer.cancel();
            verifyTimer = null;
        }
        Constant.isInCall = false;
        CallRingtoneUtils.getInstance(this).releaseMediaPlayer();
    }

    private void initGestureListener() {
        GestureDetector localVideoViewDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                if (isLocalViewBig) {
                    if (!isFastShortClick()) {
                        showOrHideButton();
                    }
                } else {
                    switchVideoView();
                }
                return true;
            }

            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                if (!isLocalViewBig) {
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) txLocalVideoView.getLayoutParams();
                    int newX = (int) (layoutParams.leftMargin + (e2.getX() - e1.getX()));
                    int newY = (int) (layoutParams.topMargin + (e2.getY() - e1.getY()));
                    if (newX < marginHorizontal) {
                        layoutParams.leftMargin = marginHorizontal;
                    } else if (newX > mScreenWidth - marginHorizontal - mSmallWidth) {
                        layoutParams.leftMargin = mScreenWidth - marginHorizontal - mSmallWidth;
                    } else {
                        layoutParams.leftMargin = newX;
                    }
                    if (newY < marginTop) {
                        layoutParams.topMargin = marginTop;
                    } else if (newY > mScreenHeight - marginBottom - mSmallHeight) {
                        layoutParams.topMargin = mScreenHeight - marginBottom - mSmallHeight;
                    } else {
                        layoutParams.topMargin = newY;
                    }
                    mSmallLayoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin, 0, 0);
                    txLocalVideoView.setLayoutParams(mSmallLayoutParams);
                }
                return true;
            }
        });
        txLocalVideoView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return localVideoViewDetector.onTouchEvent(event);
            }
        });
        GestureDetector remoteVideoViewDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                if (isLocalViewBig) {
                    switchVideoView();
                } else {
                    if (!isFastShortClick()) {
                        showOrHideButton();
                    }
                }
                return true;
            }

            @Override
            public boolean onDown(MotionEvent e) {
                return true;
            }

            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                if (isLocalViewBig) {
                    RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) txRemoteVideoView.getLayoutParams();
                    int newX = (int) (layoutParams.leftMargin + (e2.getX() - e1.getX()));
                    int newY = (int) (layoutParams.topMargin + (e2.getY() - e1.getY()));
                    if (newX < marginHorizontal) {
                        layoutParams.leftMargin = marginHorizontal;
                    } else if (newX > mScreenWidth - marginHorizontal - mSmallWidth) {
                        layoutParams.leftMargin = mScreenWidth - marginHorizontal - mSmallWidth;
                    } else {
                        layoutParams.leftMargin = newX;
                    }
                    if (newY < marginTop) {
                        layoutParams.topMargin = marginTop;
                    } else if (newY > mScreenHeight - marginBottom - mSmallHeight) {
                        layoutParams.topMargin = mScreenHeight - marginBottom - mSmallHeight;
                    } else {
                        layoutParams.topMargin = newY;
                    }
                    mSmallLayoutParams.setMargins(layoutParams.leftMargin, layoutParams.topMargin, 0, 0);
                    txRemoteVideoView.setLayoutParams(mSmallLayoutParams);
                }
                return true;
            }
        });
        txRemoteVideoView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return remoteVideoViewDetector.onTouchEvent(event);
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 告诉用户需要充值
     */
    public void showNeedChargeDialog(boolean shouldFinish) {
        NoticeDialog dialog = showNoticeDialog("温馨提醒", "余额提醒", "当前余额不足1分钟", "去充值", new OnPermissionIntroClickListener() {
            @Override
            public void onClickCancel() {
                if (shouldFinish) {
                    mPresenter.callShowHangup(mOtherId);
                }
            }

            @Override
            public void onClickOK() {
                Intent intent = new Intent(ChatVideoActivity.this, WalletActivity.class);
                startActivity(intent);
                if (shouldFinish) {
                    mPresenter.callShowHangup(mOtherId);
                }
            }
        });
    }
}
